// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/library/hgorm/hook"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"
	"hotgo/utility/validate"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"

	"hotgo/internal/library/dict"
	"hotgo/internal/model"
)

type sSysAuction struct{}

func NewSysAuction() *sSysAuction {
	return &sSysAuction{}
}

func init() {
	service.RegisterSysAuction(NewSysAuction())
	dict.RegisterFunc("auctionOption", "竞拍活动选项", service.SysAuction().Option)
}

// Model 竞拍活动ORM模型
func (s *sSysAuction) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.Auction.Ctx(ctx), option...)
}

// List 获取竞拍活动列表
func (s *sSysAuction) List(ctx context.Context, in *sysin.AuctionListInp) (list []*sysin.AuctionListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.Fields(sysin.AuctionListModel{})

	// 查询活动名称
	if in.Name != "" {
		mod = mod.WhereLike(dao.Auction.Columns().Name, "%"+in.Name+"%")
	}

	// 查询创建时间
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.Auction.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.Auction.Columns().Id)

	// 操作人摘要信息
	mod = mod.Hook(hook.MemberSummary)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取竞拍活动列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出竞拍活动
func (s *sSysAuction) Export(ctx context.Context, in *sysin.AuctionListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(sysin.AuctionExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出竞拍活动-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []sysin.AuctionExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增竞拍活动
func (s *sSysAuction) Edit(ctx context.Context, in *sysin.AuctionEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			if _, err = s.Model(ctx).
				Fields(sysin.AuctionUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改竞拍活动失败，请稍后重试！")
			}
			return
		}

		// 新增
		in.CreatedBy = contexts.GetUserId(ctx)
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.AuctionInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "新增竞拍活动失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除竞拍活动
func (s *sSysAuction) Delete(ctx context.Context, in *sysin.AuctionDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除竞拍活动失败，请稍后重试！")
		return
	}
	return
}

// View 获取竞拍活动指定信息
func (s *sSysAuction) View(ctx context.Context, in *sysin.AuctionViewInp) (res *sysin.AuctionViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Hook(hook.MemberSummary).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取竞拍活动信息，请稍后重试！")
		return
	}
	return
}

// Switch 更新竞拍活动开关
func (s *sSysAuction) Switch(ctx context.Context, in *sysin.AuctionSwitchInp) (err error) {
	var fields = []string{
		dao.Auction.Columns().Enabled,
		// ...
	}

	if !validate.InSlice(fields, in.Key) {
		err = gerror.New("开关键名不在白名单")
		return
	}

	if _, err = s.Model(ctx).WherePri(in.Id).Data(g.Map{
		in.Key: in.Value,
	}).Update(); err != nil {
		err = gerror.Wrap(err, "更新竞拍活动开关失败，请稍后重试！")
		return
	}
	return
}

// Option 获取竞拍活动选项
func (s *sSysAuction) Option(ctx context.Context) (opts []*model.Option, err error) {
	var models []*entity.Auction
	if err = s.Model(ctx).Fields(dao.Auction.Columns().Id, dao.Auction.Columns().Name).
		OrderDesc(dao.Auction.Columns().Id).Scan(&models); err != nil {
		err = gerror.Wrap(err, "获取竞拍活动选项失败！")
		return
	}
	gtime.Now().Weekday()
	opts = make([]*model.Option, len(models))
	for k, v := range models {
		opts[k] = dict.GenHashOption(v.Id, gconv.String(v.Name))
	}
	return
}
